package com.jay.io.intf;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

public class SerializableIntf implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6812168953745883299L;
	private String message;

	public String getFoo() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	private void writeObject(java.io.ObjectOutputStream out) throws IOException {
		System.out.println("writeObject invoked");
		out.writeObject(this.message == null ? "hohohahaha" : this.message);
	}

	private void readObject(java.io.ObjectInputStream in) throws IOException,
			ClassNotFoundException {
		System.out.println("readObject invoked");
		this.message = (String) in.readObject();
		System.out.println("got message:" + message);
	}

	private Object writeReplace() throws ObjectStreamException {
		System.out.println("writeReplace invoked");
		return this;
	}

	private Object readResolve() throws ObjectStreamException {
		System.out.println("readResolve invoked");
		return this;
	}

	public Object serialize() throws IOException, ClassNotFoundException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(this);
		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bais);
		return ois.readObject();
	}

	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		SerializableIntf fooimpl = new SerializableIntf();
		fooimpl.serialize();
	}
}
